<?php

namespace curd;

use surface\Component;
use surface\Functions;
use surface\Surface;

use surface\components\{Arrays, Color, Switcher, Input, Radio, Slider, Checkbox, Date, Editable, Editor, Number, Objects, Rate, Select, Sku, TableColumn, Time, TimeSelect, Transfer, Tree, Upload};

/**
 * props
 *  - default-form  表单默认项 ["options" => [], "columns" => []]
 *  - default-table 表格默认项 ["options" => [], "columns" => []]
 *  - components [
 *       "component" => '', //array 支持批量设置 | Component component的name属性名为'__RANDOM'时会随机生成字符
 *       'icon' => '', // Component
 *       'label' => '标题' // string
 *    ]
 *  - componentMap 根据组件名称映射PHP类名 会根据 components和extComponent自动加载组件
 *  - extComponent 组件扩展列 ['label' => '列名', 'components' => 同props.components]
 */
class Curd extends Component
{

    private bool $customLoad = false;

    protected function init(): void
    {
        $this->listen(self::EVENT_VIEW, function (Component $component, Surface $surface) {
            if (!$this->customLoad) {
                $surface->addScript("<script src='https://registry.npmmirror.com/sortablejs/latest/files/Sortable.min.js'></script>");
                $surface->addScript("<script src='https://registry.npmmirror.com/vuedraggable/^4/files/dist/vuedraggable.umd.min.js'></script>");
                $surface->addScript("<script src='https://registry.npmmirror.com/jsoneditor/^10/files/dist/jsoneditor.min.js'></script>");
                // 图标
                $surface->addScript('<script src="https://lf1-cdn-tos.bytegoofy.com/obj/iconpark/icons_31302_20.1ea0a7a4d9aa36da883053ab37eeda11.js"></script>');

                $surface->addStyle('<link href="https://registry.npmmirror.com/jsoneditor/^10/files/dist/jsoneditor.min.css" media="all" rel="stylesheet">');
            }

            $surface->addStyle("<style>" . file_get_contents(__DIR__ . "/style.css") . "</style>");


            //注册draggable
            $surface->register(Functions::create("app.component('draggable', window.vuedraggable)", ['app']));
            $surface->register(Functions::create(file_get_contents(__DIR__ . "/script.js"), ['app']));

            $components = $this->props['components'] ?? [];
            $extComponent = $this->props['extComponent'] ?? [];
            foreach ($extComponent as $ext) {
                $components = array_merge($components, $ext['components'] ?? []);
            }

            $componentMap = [];
            foreach ($components as $item) {
                if (!is_array($item['component'])) {
                    $item['component'] = [$item['component']];
                }
                foreach ($item['component'] as $co) {
                    if ($co instanceof Component) {
                        $co->trigger(Component::EVENT_VIEW, [$co, $surface]);
                        $componentMap[$co->el] = $co::class;
                    }
                }
            }
            $this->props('componentMap', $componentMap);

        }, false);

        $this->props([
            'components' => [
                ['label' => '输入框', 'component' => (new Input(['label' => '输入框', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-input'])],
                ['label' => '多选框', 'component' => (new Checkbox(['label' => '多选框', 'name' => '__RANDOM']))->options(["选项1", "选项2"]), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-checkbox'])],
                ['label' => '单选框', 'component' => (new Radio(['label' => '单选框', 'name' => '__RANDOM']))->options(["选项1", "选项2"]), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-radio'])],
                ['label' => '滑块', 'component' => (new Slider(['label' => '滑块', 'name' => '__RANDOM']))->props(['style' => ['min-width' => '100px']]), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-slider'])],
                ['label' => '颜色', 'component' => (new Color(['label' => '颜色', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-color'])],
                ['label' => '开关', 'component' => (new Switcher(['label' => '开关', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-switcher'])],
                ['label' => '富文本', 'component' => (new Editor(['label' => '富文本', 'name' => '__RANDOM']))->props(['style' => ['height' => "100px"]]), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-editor'])],
                ['label' => '编辑文本', 'component' => (new Editable(['label' => '编辑文本', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-editable'])],
                ['label' => '数字', 'component' => (new Number(['label' => '数字', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-number'])],
                ['label' => '数组', 'component' => (new Arrays(['label' => '数组', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-array'])],
                ['label' => '对象', 'component' => (new Objects(['label' => '对象', 'name' => '__RANDOM']))->props(
                    [
                        'columns' => [
                            (new Input(['name' => "username", 'label' => "用户名"]))->col(['span' => 12]),
                            (new Input(['name' => "password", 'label' => "密码"]))->col(['span' => 12])->item(['label-width' => 100]),
                        ]
                    ]
                ), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-object'])],
                ['label' => '评分', 'component' => (new Rate(['label' => '评分', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-rate'])],
                ['label' => '下拉框', 'component' => (new Select(['label' => '下拉框', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-select'])],
                ['label' => 'SKU', 'component' => (new Sku(['label' => 'SKU', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-sku'])],
                ['label' => '日期', 'component' => (new Date(['label' => '日期', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-date'])],
                ['label' => '时间', 'component' => (new Time(['label' => '时间', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-time'])],
                ['label' => '时间下拉', 'component' => (new TimeSelect(['label' => '时间下拉', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-time-select'])],
                ['label' => '穿梭框', 'component' => (new Transfer(['label' => '穿梭框', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-transfer'])],
                ['label' => '树V2', 'component' => (new Tree(['label' => '树V2', 'name' => '__RANDOM']))->props([
                    'style'                => ['width' => '100%'],
                    'default-expanded-keys'=> [1],
                    'height'               => 60,
                    'data' => [['id'=>1, 'label' => "L-a", 'children' => [['label' => 'L-aa']]]],
                ]), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-tree'])],
                ['label' => '上传', 'component' => (new Upload(['label' => '上传', 'name' => '__RANDOM'])), 'icon' => (new Component('iconpark-icon'))->props(['class' => 'icon', 'name' => 'i-upload'])],
            ]
        ]);
    }

    /**
     * 自定义引入样式文件
     *
     * @return $this
     */
    public function custom(): self
    {
        $this->customLoad = true;
        return $this;
    }

    /**
     * 通过数据库设置默认数据
     *
     * @param \PDO $pdo
     * @param string $database
     * @param string $tableName
     * @return $this
     */
    public function withDbSource(\PDO $pdo, string $database, string $tableName = ''): self
    {
        $query = new Query($pdo, $database);
        $tables = $query->tablesInfo();
        $table = $tables[$tableName] ?? [];
        $tableColumns = [];
        $formColumns = [];
        foreach ($table['fields'] ?? [] as $item) {
            if ($item['name'] === $table['pk']) {
                continue;
            }
            $formColumns[] = (new Input(["label" => $item['comment'] ?: $item['name'], "name" => $item['name']]));
            $tableColumns[] = (new TableColumn())->props(['label' => $item['comment'] ?: $item['name'], 'prop' => $item['name']]);
        }

        $this->props([
            "default-form" => [
                'options' => new \stdClass(),
                'columns' => $formColumns,
            ],
            "default-table" => [
                'options' => [
                    "request" => [
                        "url" => ""
                    ]
                ],
                'columns' => $tableColumns,
            ]
        ]);

        return $this;
    }

}

